package com.cci.kangdao.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.WorkOrderPrincipalTDao;
import com.cci.kangdao.dao.model.UserTechnicians;
import com.cci.kangdao.dao.model.TechnicElectronicWorkCard;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.EngineTypeTDao;
import com.cci.kangdao.dao.ServiceTechnicianFileManageDao;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.ServiceTechnicianFileManageService;
import com.cci.kangdao.utilTool.JsonUtils;

@Service
public class ServiceTechnicianFileManageServiceImpl implements ServiceTechnicianFileManageService {
	
	private static Logger logger = LoggerFactory.getLogger("ServiceTechnicianFileManageServiceImpl");
	
	private static String previewWorkCardColumnKey = "SYSTEM-WORK-CARD-COLUMN-COMPANYID:";
	
	@Autowired
	private EngineTypeTDao engineTypeTDao;
	
	@Autowired
	private RedisClientUtils redisClientUtils;
	
	@Autowired
	private ServiceTechnicianFileManageDao serviceTechnicianFileManageDao;

	@Autowired
	private WorkOrderPrincipalTDao workOrderPrincipalTDao;

	@Autowired
	private UserTDao userTDao;

	@Override
	public Map<String, Object> previewWorkCard() {
		long userId = UserThreadLocal.get().getId();
		
		// 查询出当前用户的电子工牌信息
		List<Map<String, Object>> previewWorkCard = serviceTechnicianFileManageDao.previewWorkCard(userId);
		
		// 从redis中查询出当前渠道所展示的列
		if(CollectionUtils.isNotEmpty(previewWorkCard)) {
			for(Map<String, Object> map : previewWorkCard) {
				// 查询出机型信息
				// 查询机型
				String modelIds = MapUtils.getString(map, "authorizeModelIds");
				if(StringUtils.isNotEmpty(modelIds)) {
					List<Long> ids = Arrays.stream(modelIds.split(",")).map(e -> Long.parseLong(e)).collect(Collectors.toList());
					
					List<String> engineTypes = engineTypeTDao.selectEngineTypeNameByIds(ids);
					if(CollectionUtils.isNotEmpty(engineTypes)) {
						map.put("authorizeModel", engineTypes.stream().collect(Collectors.joining(",")));
					}
				}
				
				// 从Redis中查询出当前渠道需要展示的字段
				String jsonString = redisClientUtils.get(previewWorkCardColumnKey + map.get("companyId"));
				if(StringUtils.isNotEmpty(jsonString)) {
					try {
						map.put("showColumn", JsonUtils.toJavaObject(jsonString, Map.class));
					} catch (Exception e) {
						logger.error("json转换异常 json:{}", jsonString);
					}
				}
			}
		}
		
		
		Map<String, Object> result = new HashMap<>();
		result.put("list", previewWorkCard);
		
		return result;
	}

	@Override
	public Map<String, Object> getPreviewWorkCardDetail(Map<String, Object> mapUserDetail) {

		if (mapUserDetail.get("orderId")==null || mapUserDetail.get("orderChannel") == null){
			logger.error("工单主键或者工单渠道参数有误");
		}

		Map<String, Object> result = new HashMap<>();

		Long orderId = "".equals(mapUserDetail.get("orderId").toString())?0L:Long.valueOf(mapUserDetail.get("orderId").toString());

		Long orderChannel = "".equals(mapUserDetail.get("orderChannel").toString())?0L:Long.valueOf(mapUserDetail.get("orderChannel").toString());

		//获取主副技师信息
		List<UserTechnicians> mainAndAuxiMessage = userTDao.getMainAndAuxiByOrderId(orderId);
		//存放副机师
		List<UserTechnicians> auxiMessage = new ArrayList<>();
		//存放主技师
		List<UserTechnicians> mainMessage = new ArrayList<>();
		if (CollectionUtils.isEmpty(mainAndAuxiMessage)){
			result.put("mainTechn",mainMessage);
			result.put("auxiList",auxiMessage);
			return result;
		}
		for (UserTechnicians user:mainAndAuxiMessage) {
			// 查询出当前用户的电子工牌信息
			TechnicElectronicWorkCard workCardByChannel = serviceTechnicianFileManageDao.getWorkCardByChannel(user.getID(), orderChannel);

			// 从redis中查询出当前渠道所展示的列
			if(Objects.nonNull(workCardByChannel)) {
					// 查询出机型信息
					// 查询机型
				String modelIds = workCardByChannel.getAuthorizeModelIds();
					if(StringUtils.isNotEmpty(modelIds)) {
						List<Long> ids = Arrays.stream(modelIds.split(",")).map(e -> Long.parseLong(e)).collect(Collectors.toList());

						List<String> engineTypes = engineTypeTDao.selectEngineTypeNameByIds(ids);
						if(CollectionUtils.isNotEmpty(engineTypes)) {
							String authorizeModel = engineTypes.stream().collect(Collectors.joining(","));
							workCardByChannel.setAuthorizeModel(authorizeModel);
						}
					}

					// 从Redis中查询出当前渠道需要展示的字段
					String jsonString = redisClientUtils.get(previewWorkCardColumnKey + orderChannel);
					if(StringUtils.isNotEmpty(jsonString)) {
						try {
							Map map = JsonUtils.toJavaObject(jsonString, Map.class);
							workCardByChannel.setShowColumn(map);
						} catch (Exception e) {
							logger.error("json转换异常 json:{}", jsonString);
						}
					}
				 user.setTechnicElectronicWorkCard(workCardByChannel);
				}
			if ("0".equals(user.getIsPrincipal())){
				auxiMessage.add(user);
			}else{
				mainMessage.add(user);
			}

		}

		result.put("mainTechn",mainMessage.get(0));
		result.put("auxiList",auxiMessage);
		return result;
	}


}
